package com.icesoft.core.web.suppose.safehttp.service.impl;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.BCUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import com.icesoft.core.web.suppose.safehttp.service.ICryptoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@ConditionalOnProperty(name = "icesoft.safe.sm-crypto-enable", havingValue = "true")
@Component
@Slf4j
public class Sm2Sm4CryptoService implements ICryptoService {

    @Override
    public String publicEncrypt(String publicKey, String data) {
        return new SM2(null, BCUtil.decodeECPoint(publicKey, "sm2p256v1")).encryptHex(data, KeyType.PublicKey);
    }

    @Override
    public String privateDecrypt(String privateKey, String data) {
        return new SM2(privateKey, null).decryptStr(data, KeyType.PrivateKey);
    }

    @Override
    public String symmetricEncrypt(String key, String data) {
        return SmUtil.sm4(HexUtil.decodeHex(key)).encryptHex(data);
    }

    @Override
    public String symmetricDecrypt(String key, String data) {
        return SmUtil.sm4(HexUtil.decodeHex(key)).decryptStr(data);
    }

}
